package com.iss.card.view.account;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.card.CardController;
import com.iss.card.CardController.EventType;
import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CommonValue;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.common.Tools.TimeCount;
import com.iss.card.model.UserInfo;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class AccountRetrievePasswordView extends Fragment implements IBackKeyListener,OnClickListener{
	
	
private Activity mContext;
	
	private TextView mUserName;
	//private TextView mEmail;
	private EditText retrieveInput;
	private TextView retrieveBtn;
	private Button btnConfirm;
	private CardController mCardController;
	private TimeCount timer;
	private LinearLayout mainLayout;
	private ImageButton btnJob;
	private Button btnReturn;
	private TextView tvName;
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		this.mContext = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mCardController = CardController.getInstance(mContext);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mainLayout = (LinearLayout) inflater.inflate(R.layout.account_retrieve_password, null);
		initView();
		return mainLayout;
	}
	

	public void initView(){
		
		mUserName = (TextView) mainLayout.findViewById(R.id.retrieve_password_user_name);
		//mEmail = (TextView) l.findViewById(R.id.retrieve_password_user_email);
		retrieveBtn = (TextView) mainLayout.findViewById(R.id.retrieve_GetCaptcha_button);
		retrieveInput = (EditText) mainLayout.findViewById(R.id.account_retrieve_password_captcha_input);
		btnConfirm = (Button) mainLayout.findViewById(R.id.account_retrieve_confirm_send);
		
		btnJob = (ImageButton) mainLayout.findViewById(R.id.job_button);
		btnReturn = (Button) mainLayout.findViewById(R.id.return_button);
		tvName = (TextView) mainLayout.findViewById(R.id.job_name_val);
		tvName.setText(R.string.retrieve_password_title);
		btnReturn.setVisibility(View.VISIBLE);
		
		timer = new TimeCount(mContext,60000, 1000, retrieveBtn);
		btnConfirm.setOnClickListener(this);
		retrieveBtn.setOnClickListener(this);
		btnReturn.setOnClickListener(this);
		
	}

	public void sendMessage(){
		String[] obj = doSendMessage();
		doSendMessage(obj);
	}
	private String[] doSendMessage(){
		
		String userNameVal = mUserName.getText().toString();
//		String email = mEmail.getText().toString();
		String retrieveString = retrieveInput.getText().toString();
		if(TextUtils.isEmpty(userNameVal)){ // 用户手机号
			Tools.showToast(mContext, R.string.please_write_true_num);
			return null;
		}
		
		/*if(TextUtils.isEmpty(email)){ // 邮箱	
			Tools.showToast(mContext, R.string.please_write_email_not_null);
			return null;
		}*/
		if(TextUtils.isEmpty(retrieveString)){
			Tools.showToast(mContext,R.string.account_captcha_presentation);
			return null;
		}
		/*if(!TextUtils.isDigitsOnly(retrieveString)||retrieveString.length()!= 6){
			Tools.showToast(mContext,R.string.account_input_correct_captcha);
			return null;
		}*/
						
		String[] obj = {userNameVal,retrieveString};
		
		return obj;
	}
	
	/*
	 * 注册
	 */
	private void doSendMessage(String[] obj){
		
		if(obj == null){
			return;
		}
		final String mUsrMobile = obj[0];
		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext, 
				asyncService.getNextToken(), 
				Operation.OP_SERVICE_ARG_SEND_MESSAGE, 
				WebServiceRegistrationParameter.PRODUCT_SEND_MESSAGE,
				obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_SEND_MESSAGE,
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,int index) {
				
				ResponseBean response = (ResponseBean) WebServiceUtils.
						getObjectResultToBaseInfo(result, BaseModel.class);
				if(response.getStatus().equals(ApplicationManager.RESPONSE_OK)){
					initUsrPassword(mUsrMobile);
					Tools.showToast(mContext, R.string.send_message_true);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					mCardController.sendEvent(EventType.ACTION_RETURN);
				}else {
					Tools.showToast(this, response.getMessage());
					return;
				}
			}
		});
	}
	

	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.retrieve_GetCaptcha_button:
			String mobilePhone = mUserName.getText().toString().trim();
			if (TextUtils.isEmpty(mobilePhone) || !Tools.isMobileNO(mobilePhone)){
				Tools.showToast(mContext, R.string.please_write_true_num);
				break;
			}
			String wbParaValues[] = {mobilePhone, ApplicationManager.CAPTCHA_FLAG_RETRIEVE};
			getCaptchaForForgetNumAsyncService(wbParaValues);
			
			break;
		case R.id.account_retrieve_confirm_send:
			sendMessage();
			
			break;
		case R.id.return_button:
			mCardController.sendEvent(EventType.ACTION_RETURN);
			break;
		default:
			break;
		}
	}
	private void getCaptchaForForgetNumAsyncService (String[] parameterValues){
		if (parameterValues == null){
			return;
		}
		retrieveBtn.setClickable(false);
		WebServiceAsyncService wbAsynvService = new WebServiceAsyncService();
		wbAsynvService.setParameterToAsyncService(mContext, 
				wbAsynvService.getNextToken(),
				Operation.OP_SERVICE_ARG_GET_CAPTCHA,
				WebServiceRegistrationParameter.ACCOUNT_REGISTER_GETCAPTCHA,
				parameterValues, 
				WebServiceUrlPortManager.ACTION_URL_PORT_CHECKING_MESSGE, 
				this, 
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		
		wbAsynvService.setPostExecute(new PostExecute() {
			
			@Override
			public void onAsyncServiceComplete(int token, Object result, int index) {
				// TODO Auto-generated method stub
				ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(result, BaseModel.class);
				if(response.getStatus().equals(ApplicationManager.RESPONSE_OK)){
					Tools.showToast(mContext, R.string.virification_code_sended);
					timer.start();
					
				}else {
					Tools.showToast(mContext, response.getMessage());
					timer.onFinish();
				}
			}
		});
	}
	private void initUsrPassword(String usrMobile){
		JSONObject accountObject;
		try {
			accountObject = new JSONObject(FunctionUtil.getUsrInfoForAutoLogin());
			if(accountObject.has(usrMobile)){
				accountObject.remove(usrMobile);
			}
			FunctionUtil.saveUsrInfoForAutoLogin(accountObject.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(FunctionUtil.isUserLogIn()){
			UserInfo usrinfo = new UserInfo();
			FunctionUtil.saveCurrentLogInUser(usrinfo);
		}
	}
}
